package com.walter.redis.tools.autoconfigure;

import com.walter.redis.tools.RedisUtil;
import com.walter.redis.tools.autoconfigure.properties.RedisConfigProp;
import io.micrometer.common.util.StringUtils;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.data.redis.connection.RedisStandaloneConfiguration;
import org.springframework.data.redis.connection.lettuce.LettuceConnectionFactory;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.serializer.GenericJackson2JsonRedisSerializer;
import org.springframework.data.redis.serializer.StringRedisSerializer;

import java.util.Objects;

/**
 * @author Walter
 * @date 2025/1/20 下午12:39
 **/
@ComponentScan(value = {"com.walter.redis.tools"})
@EnableConfigurationProperties({RedisConfigProp.class})
//当存在“spring.redis.host”配置项时，才执行该类
@ConditionalOnProperty(prefix = "spring.redis" , value = "host" )
@Slf4j
public class RedisAutoConfiguration {

    @Resource
    RedisConfigProp redisConfigProp;

    @Bean("redisTemplate")
    @ConditionalOnMissingBean
    public RedisTemplate<String, Object> redisTemplate(LettuceConnectionFactory connectionFactory) {
        RedisTemplate<String, Object> redisTemplate = new RedisTemplate<>();
        redisTemplate.setKeySerializer(new StringRedisSerializer());
        redisTemplate.setValueSerializer(new GenericJackson2JsonRedisSerializer());
        redisTemplate.setHashKeySerializer(new StringRedisSerializer());
        redisTemplate.setHashValueSerializer(new GenericJackson2JsonRedisSerializer());
        redisTemplate.setConnectionFactory(connectionFactory);
        //设置工具类的实例
        RedisUtil.setRedisTemplate(redisTemplate);
        log.info("RedisAutoConfiguration initialized redisTemplate and RedisUtil");
        return redisTemplate;
    }
    @Bean
    @ConditionalOnMissingBean
    public LettuceConnectionFactory connectionFactory() {
        RedisStandaloneConfiguration config = new RedisStandaloneConfiguration(redisConfigProp.getHost(), redisConfigProp.getPort());
        if (StringUtils.isNotBlank(redisConfigProp.getPassword())) {
            config.setPassword(redisConfigProp.getPassword());
        }
        if(Objects.nonNull(redisConfigProp.getDatabase())){
            config.setDatabase(redisConfigProp.getDatabase());
        }
        return new LettuceConnectionFactory(config);
    }

}
